from apps import jsonrpc, jsonrpc2
from .models import Nav, db, Banner, SiteConfig


@jsonrpc.method("Common.nav")
def nav():
    """导航信息"""
    # 查询所有顶级导航数据[parent_id为空的]，并使用sort和id进行
    nav_list = Nav.query.filter(
        Nav.parent_id == None,
        Nav.is_show == True,
        Nav.is_deleted == False
    ).order_by(
        db.desc(Nav.sort),
        db.desc(Nav.id)
    ).limit(5).all()

    data = []
    # 循环每个顶级导航模型，转换成字典
    for nav in nav_list:
        # 顶级导航有可能存在子导航，所以针对子导航也要循环，
        # 并在顶级导航中增加一个字段保存转换字典后的子导航数据
        nav.children_list = []
        top_item = nav.__to_dict__(["id", "name", "link", "children_list"])
        for child in nav.children:
            chilren_item = child.__to_dict__(["name", "id", "link"])
            nav.children_list.append(chilren_item)
        data.append(top_item)

    return data


@jsonrpc.method("Common.banner")
def banner():
    """轮播广告"""
    banner_list = Banner.query.filter(
        Banner.is_show == True,
        Banner.is_deleted == False
    ).order_by(
        db.desc(Banner.sort),
        db.desc(Banner.id)
    ).limit(8).all()

    data = []
    # 循环每个轮播广告模型，转换成字典
    for banner in banner_list:
        item = banner.__to_dict__(["id", "title", "link", "image_url"])
        data.append(item)

    return data


@jsonrpc.method("Common.siteconfig")
def siteconfig():
    """站点配置"""
    config_list = SiteConfig.query.filter(
        SiteConfig.is_show == True,
        SiteConfig.is_deleted == False
    ).order_by(
        db.desc(SiteConfig.sort),
        db.desc(SiteConfig.id)
    ).all()
    # 因为站点配置的每一行记录就是一个键值对，所以我们不需要列表保存查询结果，直接一个字典，然后遍历查询结果提取里面的键值对即可
    data = {}

    for item in config_list:
        data[item.name] = item.value

    return data
